"use client";

import React, { useState, useEffect } from "react";
import axios from "axios";
import { useParams, useRouter } from "next/navigation";
import { useUser } from "../../context/userContext";
import { Card, List, Button, Typography, Space, Modal } from "antd";
import { HomeOutlined, LeftOutlined } from "@ant-design/icons";
import styles from "@/components/Font.module.css";

const { Text } = Typography;

const container =
  "min-h-screen  flex flex-col items-center justify-start px-4 sm:px-6 lg:px-8 pt-4 pb-24";

const messageCard =
  "bg-white/60 rounded-2xl shadow-md p-6 backdrop-blur-md transition-all duration-300 hover:shadow-lg";

export default function ChatInterface() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [currentUserInfo, setCurrentUserInfo] = useState({});
  const [receiverInfo, setReceiverInfo] = useState({});
  const [confirmDeleteVisible, setConfirmDeleteVisible] = useState(false);
  const [messageIdToDelete, setMessageIdToDelete] = useState(null);

  const { user } = useUser();
  const { authorId: receiverUserId } = useParams();
  const router = useRouter();

  // 当前用户信息
  const currentUser = user || { id: null, access_token: null };

  // 后端 API 基础地址
  const baseApiUrl = "http://120.26.138.4:3000";

  // 时间格式化
  const formatTime = (timestamp) => {
    try {
      return new Date(timestamp).toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return "时间解析失败";
    }
  };

  // 获取当前用户信息
  useEffect(() => {
    if (currentUser.id) {
      axios
        .get(`${baseApiUrl}/users/info?id=${currentUser.id}`, {
          headers: {
            Authorization: `Bearer ${currentUser.access_token}`,
          },
        })
        .then((res) => setCurrentUserInfo(res.data))
        .catch((err) => console.error("获取当前用户信息失败:", err));
    }
  }, [currentUser.id, currentUser.access_token]);

  // 获取对方用户信息
  useEffect(() => {
    if (receiverUserId) {
      axios
        .get(`${baseApiUrl}/users/info?id=${receiverUserId}`)
        .then((res) => setReceiverInfo(res.data))
        .catch((err) => console.error("获取对方用户信息失败:", err));
    }
  }, [receiverUserId]);

  // 初始化消息列表
  const fetchMessages = async () => {
    if (!currentUser.id || !receiverUserId) {
      setError("请先登录或选择对话对象");
      return;
    }

    try {
      setLoading(true);
      const response = await axios.get(
        `${baseApiUrl}/messages/get-message?userId1=${currentUser.id}&userId2=${receiverUserId}`,
        {
          headers: {
            Authorization: `Bearer ${currentUser.access_token}`,
          },
        }
      );

      if (response.status === 200) {
        const newMessages = response.data.reverse();
        setMessages(newMessages);

        // 将对方的未读消息设为已读
        const unreadMessageIds = newMessages
          .filter(
            (message) =>
              message.sender_id === parseInt(receiverUserId) &&
              message.status === "unread"
          )
          .map((message) => message.id);

        unreadMessageIds.forEach(async (id) => {
          try {
            await axios.post(
              `${baseApiUrl}/messages/mark-as-read?id=${id}`,
              {},
              {
                headers: {
                  Authorization: `Bearer ${currentUser.access_token}`,
                },
              }
            );
          } catch (err) {
            console.error("标记消息为已读失败:", err);
          }
        });
      } else {
        throw new Error(`请求失败，状态码：${response.status}`);
      }
    } catch (err) {
      setError("获取消息失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMessages();
  }, [currentUser.id, receiverUserId, currentUser.access_token]);

  // 发送消息
  const handleSend = async (e) => {
    e.preventDefault();
    if (!input.trim() || !currentUser.id || !receiverUserId) return;

    try {
      const response = await axios.post(
        `${baseApiUrl}/messages/send`,
        { receiverId: receiverUserId, content: input },
        {
          headers: {
            Authorization: `Bearer ${currentUser.access_token}`,
          },
        }
      );

      if (response.status === 201) {
        setInput("");
        // 重新获取消息列表
        fetchMessages();
      } else {
        throw new Error(`请求失败，状态码：${response.status}`);
      }
    } catch (err) {
      setError("发送消息失败，请检查网络连接");
    }
  };

  // 删除消息
  const handleDelete = async (messageId) => {
    try {
      const response = await axios.delete(
        `${baseApiUrl}/messages/delete?messageId=${messageId}`,
        {
          headers: {
            Authorization: `Bearer ${currentUser.access_token}`,
          },
        }
      );

      if (response.status === 200) {
        // 重新获取消息列表
        fetchMessages();
      } else {
        throw new Error(`请求失败，状态码：${response.status}`);
      }
    } catch (err) {
      console.error("删除消息失败:", err);
    }
  };

  const showConfirmDelete = (messageId) => {
    setMessageIdToDelete(messageId);
    setConfirmDeleteVisible(true);
  };

  const handleConfirmDelete = () => {
    if (messageIdToDelete) {
      handleDelete(messageIdToDelete);
    }
    setConfirmDeleteVisible(false);
  };

  const handleCancelDelete = () => {
    setConfirmDeleteVisible(false);
  };

  return (
    <div className={container}>
      {/* 页面顶部操作栏 主页图标 + 返回图标 */}
      <div style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        width: "100%",
        padding: "0 16%",
        boxSizing: "border-box",
        zIndex: 10,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
          {/* 左侧主页图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#666",
              cursor: "pointer",
            }}
            onClick={() => router.push("/homepage/home")}
          >
            <HomeOutlined />
          </div>

          {/* 左侧返回图标 */}
          <div
            style={{
              fontSize: 30,
              color: "#666",
              cursor: "pointer",
            }}
            onClick={() => router.back()}
          >
            <LeftOutlined />
          </div>
        </div>
      </div>
      
      {/* 页面主体 */}
      <Card
        style={{
          width: "70%",
          maxWidth: 1100,
          minWidth: 600,
          background: "#ffffff",
          border: "1px solid #eee",
          boxShadow: "0 4px 12px rgba(0, 0, 0, 0.1)",
          margin: "20px auto",
        }}
      >
        {/* 标题栏,显示作者名 */}
        <div
          style={{
            position: "sticky",
            backgroundColor: "white",
            padding: "12px",
            borderBottom: "1px solid #e8e8e8",
            fontSize: 20,
            fontWeight: 600,
          }}
        >
          私信对话：{receiverInfo.display_name || "未知用户"}
        </div>
        
        {/* 可滚动的消息列表区域 */}
        <div
          style={{
            maxHeight: "600px",
            overflowY: "auto",
            padding: "16px",
            display: "flex",
            flexDirection: "column",
          }}
        >
          {/* 显示加载状态和错误信息 */}
          {loading && (
            <div
              style={{ textAlign: "center", padding: "20px", color: "#666" }}
            >
              加载中...
            </div>
          )}
          {error && (
            <div
              style={{ color: "#dc3545", textAlign: "center", padding: "10px" }}
            >
              {error}
            </div>
          )}
          
          {/* 消息列表 */}
          <List
            itemLayout="vertical"
            dataSource={messages}
            renderItem={(item) => {
              const isMine = item.sender_id === currentUser.id; // 判断消息是否是当前用户发送的
              return (
                <List.Item
                  key={item.id}
                  style={{
                    marginBottom: "12px",
                    display: "flex",
                    justifyContent: isMine ? "flex-end" : "flex-start",
                    alignItems: "flex-end",
                  }}
                >
                  {/* 显示消息内容 */}
                  <div
                    style={{
                      maxWidth: "70%",
                      padding: "12px 16px",
                      borderRadius: "20px",
                      wordWrap: "break-word",
                      backgroundColor: isMine ? "#FFF7F5" : "#ffffff",
                      border: isMine
                        ? "1px solid #D6A7A1"
                        : "1px solid #C1B7B0",
                      transition: "all 0.3s",
                    }}
                  >
                    {/* 消息发送者名称 */}
                    <Text style={{ fontWeight: 500, fontSize: "18px", color: "#333" }}>
                      {isMine
                        ? currentUserInfo.display_name || "我"
                        : receiverInfo.display_name || "对方"}
                      ：
                    </Text>
                    {/* 消息内容 */}
                    <Text style={{ color: "#555" }}>{item.content}</Text>

                    {/* 显示自己消息是否已读 */}
                    {isMine && (
                      <Text
                        type="secondary"
                        style={{
                          fontSize: "0.8em",
                          marginLeft: "8px",
                          color: item.status === "read" ? "#D6A7A1" : "#999",
                        }}
                      >
                        {item.status === "read" ? "已读" : "未读"}
                      </Text>
                    )}
                  </div>
                  
                  {/* 消息时间 */}
                  <Text
                    type="secondary"
                    style={{
                      fontSize: "12px",
                      color: "#666",
                      marginLeft: 8,
                    }}
                  >
                    {formatTime(item.createdAt || item.created_at)}
                  </Text>
                  
                  <Text
                    type="secondary"
                    style={{
                      fontSize: "12px",
                      color: "#666",
                      cursor: "pointer",
                      marginLeft: 8,
                      transition: "color 0.3s",
                    }}
                    onMouseEnter={(e) =>
                      (e.currentTarget.style.color = "#D6A7A1")
                    }
                    onMouseLeave={(e) => (e.currentTarget.style.color = "#666")}
                    onClick={() => showConfirmDelete(item.id)}
                  >
                    删除
                  </Text>
                </List.Item>
              );
            }}
          />
        </div>
        
        {/* 固定的输入框区域 */}
        <div
          style={{
            position: "sticky",
            bottom: 0,
            zIndex: 1,
            backgroundColor: "white",
            padding: "16px",
            borderTop: "1px solid #e8e8e8",
          }}
        >
          <form onSubmit={handleSend}>
            <Space style={{ width: "100%" }}>
              <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="输入消息..."
                style={{
                  flex: 1,
                  padding: "12px 16px",
                  border: "1px solid #e8e8e8",
                  borderRadius: "24px",
                  outline: "none",
                  transition: "border-color 0.3s",
                }}
                onFocus={(e) => (e.target.style.borderColor = "#D6A7A1")}
                onBlur={(e) => (e.target.style.borderColor = "#e8e8e8")}
              />
              
              <Button
                type="primary"
                htmlType="submit"
                style={{
                  padding: "12px 24px",
                  backgroundColor: "#D6A7A1",
                  color: "white",
                  border: "none",
                  borderRadius: "24px",
                  transition: "background-color 0.3s",
                  boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "#A3989D")}
                onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = "#D6A7A1")}
              >
                发送
              </Button>
            </Space>
          </form>
        </div>
        
        <Modal
          title="确认删除"
          visible={confirmDeleteVisible}
          onOk={handleConfirmDelete}
          onCancel={handleCancelDelete}
          okText="确认"
          cancelText="取消"
          okButtonProps={{ 
            style: {
              backgroundColor: "#D6A7A1",
              borderColor: "#D6A7A1",
              color: "white",
            },
            onMouseEnter: (e) => (e.currentTarget.style.backgroundColor = "#A3989D"),
            onMouseLeave: (e) => (e.currentTarget.style.backgroundColor = "#D6A7A1"),
          }}
          cancelButtonProps={{
            style: {
              color: "#666",
            },
          }}
        >
          <p style={{ color: "#555" }}>你确定要删除这条消息吗？</p>
        </Modal>
      </Card>
    </div>
  );
}